﻿using Amazon.EC2;
using Amazon.EC2.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sustainalytics.StorageSnapshot.AWS
{
    class EC2Instance
    {
        static async Task<bool> CheckInstanceStatus(string instanceId)
        {
            try
            {
                using (var ec2Client = new AmazonEC2Client(AwsCredentials.AwsAccessKey, AwsCredentials.AwsSecretKey))
                {
                    var response = await ec2Client.DescribeInstanceStatusAsync(new DescribeInstanceStatusRequest
                    {
                        IncludeAllInstances = true,
                        InstanceIds = new List<string> { instanceId }
                    }, System.Threading.CancellationToken.None);

                    return true;
                    //if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
                    //    return true;
                    //else
                    //    return false;
                }
            }
            catch (Exception ex)
            {
                //log
                return false;
            }
        }

        static async Task<bool> StartInstance(string instanceId)
        {
            try
            {
                using (var ec2Client = new AmazonEC2Client(AwsCredentials.AwsAccessKey, AwsCredentials.AwsSecretKey))
                {
                    var response = await ec2Client.StartInstancesAsync(new StartInstancesRequest
                    {
                        InstanceIds = new List<string> { instanceId }
                    });

                    if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
                        return true;
                    else
                        return false;
                }
            }
            catch (Exception ex)
            {
                //log
                return false;
            }
        }

        static async Task<bool> StopInstance(string instanceId)
        {
            try
            {
                using (var ec2Client = new AmazonEC2Client(AwsCredentials.AwsAccessKey, AwsCredentials.AwsSecretKey))
                {
                    var response = await ec2Client.StopInstancesAsync(new StopInstancesRequest
                    {
                        InstanceIds = new List<string> { instanceId }
                    });

                    if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
                        return true;
                    else
                        return false;
                }
            }
            catch (Exception ex)
            {
                //log
                return false;
            }
        }
    }
}
